package com.weilong.lw.mytest;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.LruCache;
import android.util.Log;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by Lenovo on 2016/10/8.
 */

public class NetUtil {
    /**
     * 单例对象实例
     */
    private static NetUtil instance = new NetUtil();

    public static NetUtil getInstance() {
        return instance;
    }

    public final static String ALBUM_PATH
            = Environment.getExternalStorageDirectory() + "/download_test/";
    public static String IMG;

    //手机内存的获取方式
    // 获取到可用内存的最大值，使用内存超出这个值会引起OutOfMemory异常。
    // LruCache通过构造函数传入缓存值，以KB为单位。
    int MAXMEMONRY = (int) (Runtime.getRuntime() .maxMemory() / 1024);
    private LruCache<String, Bitmap> mMemoryCache;
    private NetUtil() {
        if (mMemoryCache == null)
            //设置缓存图片的内存大小，我这里设置为手机内存的1/8
            mMemoryCache = new LruCache<String, Bitmap>(
                    MAXMEMONRY / 8) {
                @Override
                protected int sizeOf(String key, Bitmap bitmap) {
                    // 重写此方法来衡量每张图片的大小，默认返回图片数量。
                    Log.i("lw", "mMemoryCache=="+mMemoryCache+"  MAXMEMONRY=="+MAXMEMONRY);
                    return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
                }

                @Override
                protected void entryRemoved(boolean evicted, String key,
                                            Bitmap oldValue, Bitmap newValue) {
                    Log.v("lw", "hard cache is full , push to soft cache");

                }
            };
    }

    //清空缓存
    public void clearCache() {
        if (mMemoryCache != null) {
            if (mMemoryCache.size() > 0) {
                Log.d("CacheUtils",
                        "mMemoryCache.size() " + mMemoryCache.size());
                mMemoryCache.evictAll();
                Log.d("CacheUtils", "mMemoryCache.size()" + mMemoryCache.size());
            }
            mMemoryCache = null;
        }
    }

    //添加图片到缓存
    public synchronized void addBitmapToMemoryCache(String key, Bitmap bitmap) {

        if (mMemoryCache.get(key) == null) {
            if (key != null && bitmap != null) {
                mMemoryCache.put(key, bitmap);
                Log.w("lw", "mMemoryCache.put===" + mMemoryCache.put(key, bitmap));
                Log.w("lw", "key===" + mMemoryCache.get(key));
            }
        } else
            Log.w("lw", "the res is aready exits");

    }

    //从缓存中取得图片
    public synchronized Bitmap getBitmapFromMemCache(String key) {
        Bitmap bm = mMemoryCache.get(key);
        Log.w("lw", "mMemoryCache.get(key)==="+mMemoryCache.get(key));
        if (key != null) {
            return bm;
        }
        return null;
    }

    /**
     * 移除缓存
     *
     */
    public synchronized void removeImageCache(String key) {
        if (key != null) {
            if (mMemoryCache != null) {
                Bitmap bm = mMemoryCache.remove(key);
                if (bm != null)
                    bm.recycle();
            }
        }
    }

    public void getDH_IMG(final Handler handler, final String path) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setReadTimeout(2 * 1000);
                    Log.i("lw", "code===");
                    int code = conn.getResponseCode();
                    Log.i("lw", "code===" + code);
                    if (code == 200) {
                        InputStream is = conn.getInputStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(is);
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = bitmap;
                        handler.sendMessage(msg);
                    }


                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    public void getDH_IMG1(final Handler handler, final String path) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setReadTimeout(2 * 1000);
                    Log.i("lw", "code===");
                    int code = conn.getResponseCode();
                    Log.i("lw", "code===" + code);
                    if (code == 200) {
                        InputStream is = conn.getInputStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(is);
                        addBitmapToMemoryCache(IMG,bitmap);
                        Message msg = new Message();
                        msg.obj = saveFile(bitmap, IMG);
                        msg.what = 1;
                        handler.sendMessage(msg);
                    }


                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    public boolean saveFile(Bitmap bm, String fileName) throws IOException {

        try {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                File dirFile = new File(ALBUM_PATH);
                if (!dirFile.exists()) {
                    dirFile.mkdir();
                }
                File myCaptureFile = new File(ALBUM_PATH + fileName);
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
                bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
                bos.flush();
                bos.close();
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
        return false;
    }


}
